package com.cindata

import com.cindata.dictionary.*
import java.text.DecimalFormat
import java.text.SimpleDateFormat
import grails.transaction.Transactional

@Transactional
class CommunityService
{
    static scope = "singleton"

    def apiService
    def scoreApiService
    def springSecurityService

    def getCommunityScore(String zoneNumber, Long communityId)
    {
        def community = apiService.community(zoneNumber, communityId)
        def score = scoreApiService.communityLiquidityScore(communityId.toString())
        def rate = apiService.communityRate(zoneNumber, communityId.toString())
        def listingCount = 0
        def saleCount = 0
        def averPrice = 0
        def month = apiService.communityLastMonthRate(zoneNumber, communityId.toString())
        if (month?.data?.echartDate?.size() > 0)
        {
            listingCount = month?.data?.echartDate[0]?.numberCount ? month?.data?.echartDate[0]?.numberCount : 0
            averPrice = month?.data?.echartDate[0]?.price ? month?.data?.echartDate[0]?.price : 0
        }
        
        //小区1年内的小区价格走势
        def trendPriceCommunityData = []
        def trendPriceCommunityDate = []

        //小区1年内的挂牌量趋势
        def trendNetlistData = []
        def trendNetlistDate = []

        //小区1年内小区的交易量趋势
        def communityTrendSaleData = []
        def communityTrendSaleDate = []

        if(rate?.data?.echartDate)
        {
            rate?.data?.echartDate.each{
                trendPriceCommunityData.push(it?.price)
                trendPriceCommunityDate.push(it?.monthDate)
                trendNetlistData.push(it?.numberCount)
                trendNetlistDate.push(it?.monthDate)
                communityTrendSaleData.push(it?.saleCount)
                communityTrendSaleDate.push(it?.monthDate)
                saleCount = saleCount + it?.saleCount
            }
        }

        def communityScoreWeight = CommunityScoreWeight.list().get(0)		//查询权值
        def closingWeight = communityScoreWeight.closingWeight 				// 成交率权重
        def listingWeight = communityScoreWeight.listingWeight 				// 挂牌率权重
        def dealAvgDayWeight = communityScoreWeight.dealAvgDayWeight 		// 成交周期权重
        def discountrateWeight = communityScoreWeight.discountrateWeight 	// 折价比权重
        def foreclosureTimesWeight = communityScoreWeight.foreclosureTimesWeight // 法拍次数权重

        //小区配套权值
        def ifSchoolZoneScoreWeight = communityScoreWeight.schoolDistrictsWeight
        def communityTrafficScoreWeight = communityScoreWeight.trafficWeight
        def houseAgeScoreWeight = communityScoreWeight.houseAgeWeight
        def communityHospitalScoreWeight = communityScoreWeight.hospitalWeight
        def communityMallScoreWeight = communityScoreWeight.mallWeight
        def communityGreeningrateScoreWeight = communityScoreWeight.afforestationWeight
        def communityPlotratioScoreWeight = communityScoreWeight.ratioWeight
        def communityParkScoreWeight = communityScoreWeight.parkWeight
        def communityPmfeeScoreWeight = communityScoreWeight.propertyFeeWeight
        def communitySupermarketScoreWeight = communityScoreWeight.superMarketWeight
        def communityBankScoreWeight = communityScoreWeight.bankWeight

        //自然因素权值
        def scenicWeight = communityScoreWeight.scenicWeight
        def noisePullutionWeight = communityScoreWeight.noisePullutionWeight
        def airPullutionWeight = communityScoreWeight.airPullutionWeight

        //小区总分权值
        def liquidWeight = communityScoreWeight.liquidityWeight
        def surroundWeight = communityScoreWeight.assortWeight
        def natureWeight = communityScoreWeight.natureWeight

        //小区配套评分
        def ifSchoolZoneScore = 0
        def communityTrafficScore = 0
        def houseAgeScore = 0
        def communityHospitalScore = 0
        def communityMallScore = 0
        def communityGreeningrateScore = 0
        def communityPlotratioScore = 0
        def communityParkScore = 0
        def communityPmfeeScore = 0
        def communitySupermarketScore = 0
        def communityBankScore = 0

        //流动性评分
        def closingScore = 0
        def dealAvgDayScore = 0
        def listingScore = 0
        def discountrateScore = 0
        def foreclosureTimesScore = 0

        def scenicScore = 0
        def noisePullutionScore = 0
        def airPullutionScore = 0

        //小区配套总分
        def communitySurroundingScore = 0

        //小区流动性总分
        def liquidityScore = 0

        //小区自然总分
        def natureScore = 0

        def scoreArr = []
        def surroudArr = []
        def natureArr = []

        DecimalFormat df = new DecimalFormat("#.00");
        DecimalFormat df1 = new DecimalFormat("#.0");
        if (score?.closingScore)
        {
            //成交率评分
            closingScore = (score?.closingScore ? score?.closingScore : 0) * closingWeight
            //成交周期评分
            dealAvgDayScore = (score?.dealAverageDayScore ? score?.dealAverageDayScore : 0) * dealAvgDayWeight
            //挂牌率评分
            listingScore = (score?.listingScore ? score?.listingScore : 0) * listingWeight
            //折价比例评分（法拍计算）
            discountrateScore = (score?.discountrateScore ? score?.discountrateScore : 0) * discountrateWeight
            //法拍次数评分
            foreclosureTimesScore = (score?.foreclosureTimesScore ? score?.foreclosureTimesScore : 0) * foreclosureTimesWeight

            ifSchoolZoneScore = (score?.ifSchoolZoneScore ? score?.ifSchoolZoneScore : 0) * ifSchoolZoneScoreWeight
            communityTrafficScore = (score?.communityTrafficScore ? score?.communityTrafficScore : 0) * communityTrafficScoreWeight
            houseAgeScore = (score?.houseAgeScore ? score?.houseAgeScore : 0) * houseAgeScoreWeight
            communityHospitalScore = (score?.communityHospitalScore ? score?.communityHospitalScore : 0) * communityHospitalScoreWeight
            communityMallScore = (score?.communityMallScore ? score?.communityMallScore : 0) * communityMallScoreWeight
            communityGreeningrateScore = (score?.communityGreeningrateScore ? score?.communityGreeningrateScore : 0) * communityGreeningrateScoreWeight
            communityPlotratioScore = (score?.communityPlotratioScore ? score?.communityPlotratioScore : 0) * communityPlotratioScoreWeight
            communityParkScore = (score?.communityParkScore ? score?.communityParkScore : 0) * communityParkScoreWeight
            communityPmfeeScore = (score?.communityPmfeeScore ? score?.communityPmfeeScore : 0) * communityPmfeeScoreWeight
            communitySupermarketScore = (score?.communitySupermarketScore ? score?.communitySupermarketScore : 0) * communitySupermarketScoreWeight
            communityBankScore = (score?.communityBankScore ? score?.communityBankScore : 0) * communityBankScoreWeight

            scenicScore = (score?.communityRecentlyScenicScore ? score?.communityRecentlyScenicScore : 0) * scenicWeight
            noisePullutionScore = (score?.communityRecentlySubwayScore ? score?.communityRecentlySubwayScore : 0) * noisePullutionWeight
            airPullutionScore = (score?.communityRecentlyPollutionScore ? score?.communityRecentlyPollutionScore : 0) * airPullutionWeight

            communitySurroundingScore = ifSchoolZoneScore + communityTrafficScore + houseAgeScore + communityHospitalScore + communityMallScore + communityGreeningrateScore + communityPlotratioScore + communityParkScore + communityPmfeeScore + communitySupermarketScore + communityBankScore

            liquidityScore = closingScore + dealAvgDayScore + listingScore + discountrateScore + foreclosureTimesScore

            natureScore = scenicScore + noisePullutionScore + airPullutionScore

            scoreArr = "[" + df.format(score?.closingScore ? score?.closingScore : 0) + "," + df.format(score?.dealAverageDayScore ? score?.dealAverageDayScore : 0) + "," + df.format(score?.listingScore ? score?.listingScore : 0) + "," + df.format(score?.discountrateScore ? score?.discountrateScore : 0) + "," + df.format(score?.foreclosureTimesScore ? score?.foreclosureTimesScore : 0) + "]"
            surroudArr = "[" + df.format(score?.ifSchoolZoneScore ? score?.ifSchoolZoneScore : 0) + "," + df.format(score?.communityTrafficScore ? score?.communityTrafficScore : 0) + "," + df.format(score?.houseAgeScore ? score?.houseAgeScore : 0) + "," + df.format(score?.communityHospitalScore ? score?.communityHospitalScore : 0) + "," + df.format(score?.communityMallScore ? score?.communityMallScore : 0) + "," + df.format(score?.communityGreeningrateScore ? score?.communityGreeningrateScore : 0) + "," + df.format(score?.communityPlotratioScore ? score?.communityPlotratioScore : 0) + "," + df.format(score?.communityParkScore ? score?.communityParkScore : 0) + "," + df.format(score?.communityPmfeeScore ? score?.communityPmfeeScore : 0) + "," + df.format(score?.communitySupermarketScore ? score?.communitySupermarketScore : 0) + "," + df.format(score?.communityBankScore ? score?.communityBankScore : 0) + "]"
            natureArr = "[" + df.format(score?.communityRecentlyScenicScore ? score?.communityRecentlyScenicScore : 0) + "," + df.format(score?.communityRecentlySubwayScore ? score?.communityRecentlySubwayScore : 0) + "," + df.format(score?.communityRecentlyPollutionScore ? score?.communityRecentlyPollutionScore : 0) + "]"
        }

        def communityScore = liquidityScore * liquidWeight + communitySurroundingScore * surroundWeight + natureScore * natureWeight
        //查询所有押品数量
        def estateCount = Estate.executeQuery("select count(e.id) from Estate e where e.communityId = ${communityId} and e.account.id in " + Account.FilterAccountSql(User.findById(springSecurityService.principal.id)))
        //计算押品均价
        def estateList = Estate.executeQuery(" select unitPrice,loansBalance,loansEvaluateTotalPrice from Estate e where e.communityId = ${communityId} and e.account.id in " + Account.FilterAccountSql(User.findById(springSecurityService.principal.id)))
        //def list = sql.rows
        def totalUnitPrice = 0
        def sumLoansBalance = 0
        def sumLoansEvaluatePrice = 0
        def avgUnitPrice = 0
        def avgCltv = 0
        estateList.each 
        {
            totalUnitPrice += it[0] ? it[0] : 0
            sumLoansBalance += it[1] ? it[1]: 0
            sumLoansEvaluatePrice += it[2] ? it[2] : 0
        }
        if (estateList && sumLoansEvaluatePrice != 0)
        {
            //押品均价
            avgUnitPrice = totalUnitPrice / estateList.size()
            //动态抵押率
            avgCltv = sumLoansBalance / sumLoansEvaluatePrice
        }
        //成交周期
        def saleCycle = score?.dealAverageDay
        return [liquidityScore: df1.format(liquidityScore),
                        communitySurroundingScore: df1.format(communitySurroundingScore),
                        natureScore:df1.format(natureScore),
                        communityScore: df1.format(communityScore),
                        communityId: communityId,
                        scoreArr: scoreArr,
                        surroudArr: surroudArr,
                        natureArr:natureArr,
                        community: community?.data,
                        estateCount: estateCount[0],
                        avgUnitPrice: avgUnitPrice,
                        avgCltv: avgCltv,
                        listingCount: listingCount,
                        saleCount: saleCount,
                        saleCycle: saleCycle,
                        averPrice: averPrice,
                        trendPriceCommunityData: trendPriceCommunityData,
                        trendPriceCommunityDate: trendPriceCommunityDate,
                        trendNetlistData: trendNetlistData,
                        trendNetlistDate: trendNetlistDate,
                        communityTrendSaleData: communityTrendSaleData,
                        communityTrendSaleDate: communityTrendSaleDate,
                        score: score]
    }
}

